package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.PlatformUserPotential;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

public class PlayerPotentialDaoImpl  extends TempDataObjectDao<PlatformUserPotential> {
    @Override
    protected boolean addData(PlatformUserPotential data) {
        data.setBeginWriteTime();
        String sql = "replace into t_s_user_potential (platformUserId,potential) values (?,?)";
        getDb().setConnName(DbNameStrategy.getServerDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.VARCHAR, data.getPlatformUserId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getPotential()));

        if (getDb().executeNoneQuery(sql, para) > 0) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean updateData(PlatformUserPotential data) {
        return true;
    }

    public PlatformUserPotential getPlayerPotential(String platformUserId) {
        ResultSet rs = null;
        CallableStatement call = null;
        PlatformUserPotential data = null;
        String sql = "select * from t_s_user_potential where platformUserId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setString(1, platformUserId);
            rs = call.executeQuery();
            while (rs.next()) {
                data = parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return data;
    }

    @Override
    protected PlatformUserPotential parseData(ResultSet rs) throws SQLException {
        String platformUserId = rs.getString("platformUserId");
        int potential = rs.getInt("potential");
        PlatformUserPotential platformUserPotential = new PlatformUserPotential();
        platformUserPotential.setPlatformUserId(platformUserId);
        platformUserPotential.setPotential(potential);
        return platformUserPotential;
    }
}
